package com.stone.starter.redis.client;

import org.springframework.data.redis.connection.DefaultStringRedisConnection;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.lang.NonNull;

/**
 * redis缓存客户端，使用RedisTemplate，默认字符类型
 *
 * @author Mr_wenpan@163.com 2021/7/16 10:18 上午
 */
public class RedisCacheClient extends RedisTemplate<String, String> {

    private RedisCacheClient() {
        RedisSerializer<String> stringSerializer = new StringRedisSerializer();
        setKeySerializer(stringSerializer);
        setValueSerializer(stringSerializer);
        setHashKeySerializer(stringSerializer);
        setHashValueSerializer(stringSerializer);
    }

    public RedisCacheClient(RedisConnectionFactory connectionFactory) {
        this();
        setConnectionFactory(connectionFactory);
        afterPropertiesSet();
    }

    @Override
    @NonNull
    protected RedisConnection preProcessConnection(@NonNull RedisConnection connection, boolean existingConnection) {
        // 返回Redis连接，在redisTemplate执行命令的时候被吊起
        return new DefaultStringRedisConnection(connection);
    }
}